import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { Button, Menu, message } from 'antd';
import { IntentionLibrary } from 'admin/components/IntentionLibrary';
import QALibrary from 'admin/components/QALibrary';
// import BasicWordLibrary from 'admin/components/BasicWordLibrary';
import BasicResource from 'admin/components/BasicResource';
import FlowManage from 'admin/components/FlowManage';

import './flow.scss';
import FlowDebug from 'admin/components/FlowDebug';
import SoundLibrary from 'admin/components/SoundLibrary';
import { getStore } from 'store/store';
import qs from 'query-string';
import FlowGlobalSet from 'admin/components/FlowGlobalSet';
import { LeftOutlined } from '@ant-design/icons';
import { debounce } from 'lodash';
import { getRobotInfo, offVersion, onVersion } from 'admin/servers/servers';
import { modifyRobot } from 'admin/servers/servers';
import { GetRobotInfo } from 'admin/schema/RobotVersion';

const Flow: React.FC = () => {
  const history = useHistory();
  // 路由location
  const location = useLocation();
  // URL查询字符串=>对象
  const query = useMemo(() => {
    return qs.parse(location.search);
  }, [location.search]);
  // 地址栏拿机器人Id
  const robotId = Number(query.robotId);
  /**
   * 当前选中的菜单key
   */
  const currentMenu = query.type ? String(query.type) : 'flowManage';

  const [loading, setLoading] = useState(false); // 加载
  const [robotInfo, setRobotInfo] = useState<GetRobotInfo>(undefined); // 机器人信息
  const [robotName, setRobotName] = useState<string>('');
  const [versionStatus, setVersionStatus] = useState<'online' | 'offline'>('' as any);
  const [versionId, setVersionId] = useState<number>(0);
  const [menuData, setMenuData] = useState<any>([]);
  const [isshow, setIsshow] = useState(true);
  const [aiModalTurnOn, setAiModalTurnOn] = useState(false); // 是否启用大模型

  /**
   * 获取机器人详情
   * @param robotId
   */
  const getRobotDetail = useCallback(async () => {
    if (!robotId) return;
    try {
      setLoading(true);
      const res = await getRobotInfo({ robotId });
      setLoading(false);
      const { robotName, versionStatus, versionId, modelFlag } = res.data;
      setRobotInfo(res.data ?? undefined);
      setRobotName(robotName);
      setVersionStatus(versionStatus);
      setVersionId(versionId);
      setAiModalTurnOn(!!modelFlag);
      const menus = getMenuData(versionId);
      setMenuData(menus);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }, [robotId]);

  useEffect(() => {
    getRobotDetail();
    // 强制根据store里面的内容渲染页面
    getStore().addChangeEvent('isFullScreen', val => {
      setIsshow(prev => !prev);
    });

    return () => {
      console.log('leave out >>>>>flow page!!!');
    };
  }, [getRobotDetail, query.robotId]);

  // 横向菜单配置
  const getMenuData = (versionId: number) => [
    {
      key: 'flowManage',
      title: '流程管理',
      component: <FlowManage versionId={versionId} key="flowManage" />,
    },
    {
      key: 'flowGlobalSet',
      title: '全局设置',
      component: <FlowGlobalSet versionId={versionId} key="flowGlobalSet" />,
    },
    {
      key: 'soundLibrary',
      title: '录音库',
      component: <SoundLibrary versionId={versionId} key="soundLibrary" />,
    },
    {
      key: 'intentionLibrary',
      title: '意图库',
      component: <IntentionLibrary versionId={versionId} key="intentionLibrary" />,
    },
    {
      key: 'QALibrary',
      title: '问答库',
      component: <QALibrary versionId={versionId} key="QALibrary" />,
    },
    // {
    //   key: 'basicWordLibrary',
    //   title: '基础词库',
    //   component: <BasicWordLibrary versionId={versionId} key="basicWordLibrary" />,
    // },
    {
      key: 'basicResource',
      title: '基础资源',
      component: <BasicResource versionId={versionId} key="basicResource" />,
    },
    {
      key: 'processDebug',
      title: '流程调试',
      component: <FlowDebug versionId={versionId} key="processDebug" />,
    },
  ];
  /**
   * 更新机器人状态：上线、下线操作
   */
  const updateVersionStatus = async () => {
    if (!versionId) return;
    if (versionStatus === 'online') {
      // 1-上线状态，则请求接口进行【下线】
      try {
        await offVersion({
          versionId: versionId,
        });
        setVersionStatus('offline');
        message.success(`下线成功`);
      } catch (error) {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      }
    } else {
      // 2-草稿，下线，则请求接口进行【上线】
      try {
        await onVersion({
          versionId: versionId,
        });
        setVersionStatus('online');
        message.success(`上线成功`);
      } catch (error) {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      }
    }
  };

  /**
   * 更新大模型状态
   * @param flag
   */
  const updateAiModalFlag = async (flag: boolean) => {
    setLoading(true);
    await modifyRobot(robotInfo?.robotId, {
      robotName: robotInfo?.robotName,
      robotDescribe: robotInfo?.robotDescribe,
      modelFlag: flag ? 1 : 0,
    }).catch(() => {
      setLoading(false);
    });
    setLoading(false);
    getRobotDetail();
  };

  return (
    <>
      <div className="flow">
        <div className="nav flow-nav">
          <Button
            type="link"
            onClick={() => {
              history.push(`/webapp/outbound/ai/robots`);
            }}
          >
            <LeftOutlined />
            返回
          </Button>
          <div className="title">{robotName}</div>
          <div className="nav-right" style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <Button
              type="primary"
              disabled={loading}
              onClick={() => updateAiModalFlag(!aiModalTurnOn)}
            >
              {aiModalTurnOn ? '停用大模型' : '启动大模型'}
            </Button>
            <Button
              type="primary"
              disabled={loading}
              onClick={debounce(() => updateVersionStatus(), 1000)}
            >
              {versionStatus === 'online' ? '下线' : '上线'}
            </Button>
          </div>
        </div>
        {menuData.length > 0 && (
          <Menu
            className="flow-menu"
            mode="horizontal"
            selectedKeys={[currentMenu]}
            style={{ display: isshow ? 'block' : 'none' }}
          >
            {menuData.map((item: any) => {
              return (
                <Menu.Item
                  key={item.key}
                  className="custom-menu-item unselect-words"
                  onClick={() => {
                    history.replace(
                      `/webapp/outbound/ai/robots/version/flow?robotId=${robotId}&type=${item.key}`
                    );
                  }}
                >
                  {item.title}
                </Menu.Item>
              );
            })}
          </Menu>
        )}
        {/* 当前展示的组件 */}
        {menuData.map((item: { key: string; component: any }) => {
          return item.key === currentMenu && item.component;
        })}
      </div>
    </>
  );
};

export default Flow;
